/**
 * 
 */
package org.xnat.xnatfs.webdav;

import org.apache.log4j.Logger;

/**
 * @author blezek
 * 
 */
public class Scan extends VirtualDirectory {
  private static final Logger logger = Logger.getLogger ( Scan.class );

  public Scan ( XNATFS x, String path, String n, String url ) {
    super ( x, path, n, url );
    elementURL = mURL + n.toLowerCase () + "?format=json";
    elementURL = mURL + "resources?format=json";
    childKeys.add ( "label" );
    childKeys.add ( "xnat_abstractresource_id" );
    childKeys.add ( "id" );
    verboseDirectoryName = "Resources";
  }

  @Override
  public VirtualResource child ( String childName ) {
    if ( xnatfs.useVerboseFolders () && !verboseDirectory ) {
      // this object is not the verbose folder, but we must create one.
      if ( childName.equals ( verboseDirectoryName ) ) {
        VirtualDirectory d = new Scan ( xnatfs, absolutePath, verboseDirectoryName, mURL );
        d.setVerboseDirectory ( true );
        return d;
      }
    }

    if ( childName.equals ( RESOURCES ) ) {
      VirtualDirectory d = new Resources ( xnatfs, absolutePath, childName, mURL );
      d.setVerboseDirectory ( true );
      return d;
    }
    try {
      getElementList ();
    } catch ( Exception e ) {
      logger.error ( "Failed to cache children", e );
    }

    if ( childMap.containsKey ( childName ) ) {
      logger.debug ( "child: create " + childName );
      VirtualResource bundle = new Bundle ( xnatfs, absolutePath, childName, mURL + "resources/" + childName + "/" );
      return bundle;
    }
    return null;
  }
}
